In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
import numpy as np
import random
import numpy as np
import matplotlib.pyplot as plt
import math
from sklearn.utils import shuffle
import cv2
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from tqdm import tqdm
# Visualizations will be shown in the notebook.
%matplotlib inline
# TODO: Fill this in based on where you saved the training and testing data
training_file = '../data/train.p'
validation_file='../data/valid.p'
testing_file = '../data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_validation, y_validation = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
#X_train = X_train[1:1000]
#y_train = y_train[1:1000]
assert(len(X_train) == len(y_train))
assert(len(X_validation) == len(y_validation))
assert(len(X_test) == len(y_test))
print()
print("Image Shape: {}".format(X_train[0].shape))
print()
print("Training Set: {} samples".format(len(X_train)))
print("Validation Set: {} samples".format(len(X_validation)))
print("Test Set: {} samples".format(len(X_test)))
print(y_train.shape)
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_validation.shape[0]
# TODO: Number of testing examples.
n_test = X_test.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape
# TODO: How many unique classes/labels there are in the dataset.
n_classes = np.unique(y_train).shape[0]
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
#distribution of images in training set
n_classes, class_counts = np.unique(y_train, return_counts = True)
signs = list(range(43))
plt.figure(figsize=(5,5))
plt.bar(signs, class_counts)
plt.suptitle('Sign appearance in training set', fontsize=16)
#distribution of images in validation set
n_classes, class_counts = np.unique(y_validation, return_counts = True)
signs = list(range(43))
plt.figure(figsize=(5,5))
plt.bar(signs, class_counts)
plt.suptitle('Sign appearance in validation set', fontsize=16)
#distribution of images in test set
n_classes, class_counts = np.unique(y_test, return_counts = True)
signs = list(range(43))
plt.figure(figsize=(5,5))
plt.bar(signs, class_counts)
plt.suptitle('Sign appearance in test set', fontsize=16)
#show random image
for signtype in tqdm(n_classes):
img_set = X_train[y_train == signtype]
plt.figure(figsize=(20,3))
plt.suptitle('Sign: %s' %signtype, fontsize=16)
for index in range(10):
plt.subplot(1, 10, index+1)
plt.imshow(img_set[random.randint(0,img_set.shape[0]-1)])
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
#random translation
def translate(image):
rnd = random.randint(1, 8)
image = image[rnd:rnd+24,rnd:rnd+24,:]
image = np.pad(image, ((0,8),(0,8),(0,0)), 'constant')
return image
#zooming
def zoom(image):
zoom_factor = .7 + .6*random.random()
size = math.floor(zoom_factor*32)
if size < 32:
zoom = cv2.resize(image,(size,size))
zoom = np.pad(zoom, ((0,32-size),(0,32-size),(0,0)), 'constant')
elif size >= 32:
zoom = cv2.resize(image,(size,size))
zoom=zoom[math.floor((size-32)/2):math.floor((size-32)/2)+32,math.floor((size-32)/2):math.floor((size-32)/2)+32]
return zoom
#noise
def noise(image):
noise = np.zeros_like(image)
randmask = np.random.normal(size = (32,32))
randmask = np.clip((randmask*64+128),0,255).astype(int)
noise[:,:,0] = randmask
noise[:,:,1] = randmask
noise[:,:,2] = randmask
image = cv2.addWeighted(image, 0.9, noise, 0.1, 0)
return image
#random flip
def flip(image):
image = cv2.flip(image, 1)
return image
#random rotation
def rotate(image):
rnd = random.randint(-20,20)
M = cv2.getRotationMatrix2D((16, 16), rnd, 1)
image = cv2.warpAffine(src=image, M=M, dsize=(32, 32))
return image
def augment_image(image):
rnd = random.randint(1,4)
if rnd == 1:
img = translate(image)
elif rnd == 2:
img = zoom(image)
elif rnd == 3:
img = noise(image)
elif rnd == 4:
img = rotate(image)
elif rnd == 5:
img = flip(image)
return img
#Create augmented images using the augmentation techniques above so there are equal numbers of each type of sign
n_classes, class_counts = np.unique(y_train, return_counts = True)
augmented_images = []
augmented_labels = []
desired = 5000
for signtype in tqdm(n_classes):
augment_set = X_train[y_train == signtype]
# plt.figure(figsize=(20,3))
# for index in range(10):
# plt.subplot(1, 10, index+1)
# plt.imshow(augment_set[random.randint(0,augment_set.shape[0]-1)])
count = class_counts[signtype]
while (count < desired):
rnd = random.randint(0,augment_set.shape[0]-1)
augmented_images.append(augment_image(augment_image(augment_set[rnd])))
augmented_labels.append(signtype)
count += 1
# plt.figure(figsize=(20,3))
# for index in range(10):
# plt.subplot(1, 10, index+1)
# plt.imshow(augmented_images[-(random.randint(1,desired-class_counts[signtype]))])
#concatenate augmented images to original training images to create augmented data set
X_train = np.concatenate([X_train, np.array(augmented_images)])
y_train = np.concatenate([y_train, np.array(augmented_labels)])
#apply grayscale and histogram equalization
X_train = np.array([np.expand_dims(cv2.equalizeHist(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)), axis = 2) for image in X_train])
X_validation = np.array([np.expand_dims(cv2.equalizeHist(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)), axis = 2) for image in X_validation])
#visualize augmented data set
aug_classes, aug_counts = np.unique(y_train, return_counts = True)
for signtype in tqdm(aug_classes):
augment_set = X_train[y_train == signtype]
plt.figure(figsize=(20,3))
plt.suptitle('Sign: %s, %s images' %(signtype,augment_set.shape[0]), fontsize=16)
for index in range(10):
rnd = random.randint(0,augment_set.shape[0]-1)
plt.subplot(1, 10, index+1).set_title('%s, %s' %(rnd, augment_set[rnd].shape))
plt.imshow(augment_set[rnd].squeeze())
#Normalize
X_train = np.add(X_train,-128)/128
X_validation = np.add(X_validation,-128)/128
#preprocess test data
X_test = np.array([np.expand_dims(cv2.equalizeHist(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)), axis = 2) for image in X_test])
X_test = np.add(X_test,-128)/128
### Define your architecture here.
### Feel free to use as many code cells as needed.
mu = 0
sigma = 0.1
# Store layers weight & bias
weights = {
'wc1': tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma), name='wc1'),
'wc2': tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma), name='wc2'),
'wc3': tf.Variable(tf.truncated_normal(shape=(3, 3, 16, 64), mean = mu, stddev = sigma), name='wc3'),
'wc4': tf.Variable(tf.truncated_normal(shape=(3, 3, 64, 128), mean = mu, stddev = sigma), name='wc4'),
'wd1': tf.Variable(tf.truncated_normal(shape=(3*3*128, 120), mean = mu, stddev = sigma), name='wd1'),
'wd2': tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma), name='wd2'),
'out': tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma), name='out')}
biases = {
'bc1': tf.Variable(tf.zeros(6), name='bc1'),
'bc2': tf.Variable(tf.zeros(16), name='bc2'),
'bc3': tf.Variable(tf.zeros(64), name='bc3'),
'bc4': tf.Variable(tf.zeros(128), name='bc4'),
'bd1': tf.Variable(tf.zeros(120), name='bd1'),
'bd2': tf.Variable(tf.zeros(84), name='bd2'),
'out': tf.Variable(tf.zeros(43), name='bout')}
def GaddyNet(x, keep_prob = 0.5):
# TODO: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
conv1 = tf.nn.conv2d(x, weights['wc1'], strides=[1, 1, 1, 1], padding='VALID')
conv1 = tf.nn.bias_add(conv1, biases['bc1'])
print("Conv1 Layer shape: {}".format(conv1[0].shape))
# TODO: Activation.
conv1 = tf.nn.relu(conv1)
# TODO: Pooling. Input = 28x28x6. Output = 14x14x6.
pool1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# TODO: Layer 2: Convolutional. Output = 10x10x16.
conv2 = tf.nn.conv2d(pool1, weights['wc2'], strides=[1, 1, 1, 1], padding='VALID')
conv2 = tf.nn.bias_add(conv2, biases['bc2'])
print("Conv2 Layer shape: {}".format(conv2[0].shape))
# TODO: Activation.
conv2 = tf.nn.relu(conv2)
# TODO: Pooling. Input = 10x10x16. Output = 5x5x16.
pool2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# new conv layer: 5x5x16 to 3x3x64
conv3 = tf.nn.conv2d(pool2, weights['wc3'], strides=[1, 1, 1, 1], padding='VALID')
conv3 = tf.nn.bias_add(conv3, biases['bc3'])
conv3 = tf.nn.relu(conv3)
print("Conv3 Layer shape: {}".format(conv3[0].shape))
# new conv layer: 3x3x64 to 3x3x128
conv4 = tf.nn.conv2d(conv3, weights['wc4'], strides=[1, 1, 1, 1], padding='SAME')
conv4 = tf.nn.bias_add(conv4, biases['bc4'])
conv4 = tf.nn.relu(conv4)
print("Conv4 Layer shape: {}".format(conv4[0].shape))
# TODO: Flatten. Input = 3x3x128. Output = 1152.
fc1 = tf.reshape(conv4, [-1, weights['wd1'].get_shape().as_list()[0]])
# TODO: Layer 3: Fully Connected. Input = 1152. Output = 120.
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
# TODO: Activation.
fc1 = tf.nn.relu(fc1)
fc1 = tf.nn.dropout(fc1, keep_prob)
# TODO: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2 = tf.add(tf.matmul(fc1, weights['wd2']), biases['bd2'])
fc2 = tf.nn.relu(fc2)
#fc2 = tf.nn.dropout(fc2, keep_prob)
# TODO: Layer 5: Fully Connected. Input = 84. Output = 43.
logits = tf.add(tf.matmul(fc2, weights['out']), biases['out'])
return logits, conv1, pool1, conv2, pool2, conv3, conv4, fc1, fc2
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32, (None))
rate = tf.placeholder(tf.float32, (None))
one_hot_y = tf.one_hot(y, 43)
EPOCHS = 8
BATCH_SIZE = 128
#rate = 0.001 #rate is defined dynamically in the training session in the cell below
beta = 0.01
logits, conv1, pool1, conv2, pool2, conv3, conv4, fc1, fc2 = GaddyNet(x, keep_prob)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
# Loss function using L2 Regularization - from https://www.ritchieng.com/machine-learning/deep-learning/tensorflow/regularization/
#loss_operation = tf.reduce_mean(loss_operation + beta * tf.nn.l2_loss(weights['wc1'])
# + beta * tf.nn.l2_loss(weights['wc2'])
# + beta * tf.nn.l2_loss(weights['wc3'])
# + beta * tf.nn.l2_loss(weights['wc4'])
# + beta * tf.nn.l2_loss(weights['wd1'])
# + beta * tf.nn.l2_loss(weights['wd2'])
# + beta * tf.nn.l2_loss(weights['out']))
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
#loss = (tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
# logits=out_layer, labels=tf_train_labels)) +
# 0.01*tf.nn.l2_loss(hidden_weights) +
# 0.01*tf.nn.l2_loss(out_weights))
# Loss function using L2 Regularization
# regularizer = tf.nn.l2_loss(weights)
# loss = tf.reduce_mean(loss + beta * regularizer)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
for i in range(EPOCHS):
X_train, y_train = shuffle(X_train, y_train)
lr = 0.001/(1+i*0.0001)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5, rate: lr})
train_accuracy = evaluate(X_train, y_train)
validation_accuracy = evaluate(X_validation, y_validation)
print("EPOCH {} ...".format(i+1))
print("Train Accuracy = {:.3f}".format(train_accuracy))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
print()
saver.save(sess, './lenet')
print("Model saved")
n_classes, class_counts = np.unique(y_train, return_counts = True)
sign_accuracy = np.zeros_like(n_classes).astype(float)
with tf.Session() as sess:
saver.restore(sess, './lenet')
test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
for signtype in n_classes:
img_set = X_test[y_test == signtype]
test_accuracy = evaluate(img_set, y_test[y_test == signtype])
print("Test Accuracy %s = {:.3f}".format(test_accuracy) %signtype)
sign_accuracy[signtype] = test_accuracy
plt.figure(figsize=(20,5))
plt.bar(n_classes, sign_accuracy)
plt.suptitle('Sign accuracy in test set', fontsize=16)
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
import matplotlib.image as mpimg
#create labels
web_labels = [1, 33, 14, 35, 13]
web_labels = np.array(web_labels)
#import, resize, and display images from web
#file_list = os.listdir("Traffic Signs/")
file_list = ['30kph sign.jpg', 'right turn.jpg', 'stop sign.jpg', 'straight ahead.jpg', 'yield.jpg']
web_images = []
index = 1
plt.figure(figsize=(20,3))
for name in file_list:
image = mpimg.imread('./Traffic Signs/%s' %(name))
image = cv2.resize(image,(32,32))
plt.subplot(1, 5, index).set_title('%s, %s' %(web_labels[index-1], image.shape))
plt.imshow(image)
web_images.append(image)
index +=1
#apply grayscale and histogram equalization
web_images = np.array([np.expand_dims(cv2.equalizeHist(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)), axis = 2) for image in web_images])
#visualize preprocessed images
plt.figure(figsize=(20,3))
index = 1
for m in web_images:
plt.subplot(1, 5, index).set_title('%s, %s' %(web_labels[index-1], image.shape))
plt.imshow(m.squeeze())
index +=1
#normalize images
web_images = np.add(web_images,-128)/128
with tf.Session() as sess:
saver.restore(sess, './lenet')
test_accuracy = evaluate(web_images, web_labels)
maxs = sess.run(tf.argmax(logits, 1), feed_dict={x: web_images, keep_prob: 1})
print(maxs)
with tf.Session() as sess:
saver.restore(sess, './lenet')
test_accuracy = evaluate(web_images, web_labels)
print("Test Accuracy = {:.3f}".format(test_accuracy))
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
saver.restore(sess, './lenet')
top_softmax = sess.run(tf.nn.top_k(tf.nn.softmax(logits), k=5), feed_dict={x: web_images, keep_prob: 1})
print(top_softmax)
#web_labels = [1, 33, 14, 35, 13]
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
img = np.expand_dims(web_images[1], axis=0)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
outputFeatureMap(img, conv1)
img = np.expand_dims(web_images[1], axis=0)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
outputFeatureMap(img, pool1)
View Conv2 for right turn sign
img = np.expand_dims(web_images[1], axis=0)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
outputFeatureMap(img, conv2)
View pool2 for right turn sign
img = np.expand_dims(web_images[1], axis=0)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
outputFeatureMap(img, pool2)